import collections
import os
from pathlib import Path
from random import shuffle

from file_utils import JsonOps


class Data(object):
    '''数据处理'''

    __ROOT_PATH = Path(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')).as_posix()

    @classmethod
    def get_one_file_data(cls, file_path):
        '''获取某个指定单词集的数据'''
        return JsonOps.read(file_path)


    @classmethod
    def get_file_path_by_name(cls, name):
        '''根据文件名字获取单词集的完整路径'''
        all_files = cls.get_file(cls.__ROOT_PATH)
        for file in all_files:
            if "error_data" in os.path.basename(file):
                continue
            if name in os.path.basename(file):
                return file
        print(f">> 未找到名字为{name}的文件！！")


    @classmethod
    def get_all_word(cls):
        '''获取data路径下所有单词合集 error_data除外'''
        all_file_path = cls.get_file(cls.__ROOT_PATH)
        data_set = dict()
        for file_path in all_file_path:
            data = cls.get_one_file_data(file_path)
            data_set.update(data)
        return data_set

    @classmethod
    def get_error_word(cls):
        """获取所有的错误单词"""
        file_path = Path(os.path.join(os.path.join(cls.__ROOT_PATH, "error_data"), "error_data.json")).as_posix()
        if not os.path.isfile(file_path):
            print(f">> 未找到名字为<error_data>的文件！！")
            return
        data = cls.get_one_file_data(file_path)
        result = {}
        for key, value in data.items():
            result[key] = value.get(key, " ")
        return result



    @classmethod
    def get_file(cls, root_path, all_files=[]):
        '''
        递归函数，遍历该文档目录和子目录下的所有文件，获取其path
        '''
        files = os.listdir(root_path)
        for file in files:
            if not os.path.isdir(os.path.join(root_path, file)):  # not a dir
                all_files.append(Path(os.path.join(root_path, file)).as_posix())
            else:  # is a dir
                cls.get_file((Path(os.path.join(root_path, file)).as_posix()), all_files)
        return all_files

    @classmethod
    def random_dic(cls, dicts, num=None):
        '''打乱字典排序 返回有序字典'''
        dict_key_ls = list(dicts.keys())
        shuffle(dict_key_ls)
        new_dic = collections.OrderedDict()
        if num is not None and num <= len(dict_key_ls) - 1:
            dict_key_ls = dict_key_ls[0: num]
        for key in dict_key_ls:
            new_dic[key] = dicts.get(key)
        return new_dic
